package com.cet.programmercarl.algorithmperformancanalysis.链表;

/**
 * @program: algorithm
 * @description: 链表环存在问题
 * @author: 陈恩涛
 * @create: 2022-03-11 22:07
 **/
public class LC142 {

    /**
     * 提示：1、快慢指针，速度不同(fast一次移动两个节点，slow一次移动一个节点)能相遇，证明有环
     *      2、环的相遇节点：数学公式推演 2*(x+y)=x+y+n*(y+z) => x=(n-1)*(y+z)+z
     * @param head
     * @return
     */
    public static ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;

            // 相遇，有环
            if (fast == slow) {
                ListNode temp = head;
                while (temp != fast) {
                    temp = temp.next;
                    fast = fast.next;
//                    if (temp == fast) {
//                        return fast;
//                    }
                }
                return fast;
            }
        }
        return null;
    }

    public static void main(String[] args) {

    }
}
